<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" size="small" @click="handleEditProfile">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </template>

          <div class="profile-info">
                        <div class="avatar-section">
              <div class="avatar-wrapper">
                <el-avatar
                  :size="80"
                  :src="userInfo.avatar ? userInfo.avatar : ''"
                  class="user-avatar"
                >
                  <el-icon><User /></el-icon>
                </el-avatar>
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="uploadAvatar"
                  accept="image/*"
                >
                  <el-button size="small" type="primary" class="upload-btn">
                    <el-icon><Edit /></el-icon>
                    更换头像
                  </el-button>
                </el-upload>
              </div>
              <h3 class="username">{{ userInfo.displayName || userInfo.account }}</h3>
              <p class="user-role">{{ userInfo.role || '普通用户' }}</p>
            </div>

            <el-divider />

            <div class="info-list">
              <div class="info-item">
                <span class="label">账号:</span>
                <span class="value">{{ userInfo.account || 'N/A' }}</span>
              </div>
              <div class="info-item">
                <span class="label">显示名称:</span>
                <span class="value">{{ userInfo.displayName || 'N/A' }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ userInfo.email || '暂无邮箱' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号:</span>
                <span class="value">{{ userInfo.phone || '暂无联系方式' }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态:</span>
                <el-tag :type="userInfo.isActived ? 'success' : 'danger'" size="small">
                  {{ userInfo.isActived ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDate(userInfo.createdAt) }}</span>
              </div>
              <div class="info-item">
                <span class="label">最后更新:</span>
                <span class="value">{{ formatDate(userInfo.updatedAt) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧设置区域 -->
      <el-col :span="16">
        <!-- 基本信息编辑 -->
        <el-card class="setting-card" v-if="showProfileEdit">
          <template #header>
            <div class="card-header">
              <span>编辑基本信息</span>
            </div>
          </template>

          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
          >
            <el-form-item label="账号" prop="account">
              <el-input
                v-model="profileForm.account"
                placeholder="请输入账号"
                maxlength="50"
                show-word-limit
                disabled
              />
            </el-form-item>

            <el-form-item label="显示名称" prop="displayName">
              <el-input
                v-model="profileForm.displayName"
                placeholder="请输入显示名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="profileForm.email"
                placeholder="请输入邮箱"
                type="email"
              />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="profileForm.phone"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSaveProfile" :loading="saveLoading">
                保存修改
              </el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 密码修改 -->
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>

          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input
                v-model="passwordForm.currentPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
                maxlength="50"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
                maxlength="50"
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
                maxlength="50"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 安全设置 -->
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
            </div>
          </template>

          <div class="security-settings">
            <div class="setting-item">
              <div class="setting-info">
                <h4>登录通知</h4>
                <p>当有新设备登录时发送邮件通知</p>
              </div>
              <el-switch v-model="securitySettings.loginNotification" />
            </div>

            <el-divider />

            <div class="setting-item">
              <div class="setting-info">
                <h4>两步验证</h4>
                <p>启用两步验证以提高账户安全性</p>
              </div>
              <el-switch v-model="securitySettings.twoFactorAuth" />
            </div>

            <el-divider />

            <div class="setting-item">
              <div class="setting-info">
                <h4>会话管理</h4>
                <p>管理当前登录的设备</p>
              </div>
              <el-button type="primary" size="small" @click="handleSessionManagement">
                管理会话
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 会话管理对话框 -->
    <el-dialog
      v-model="sessionDialogVisible"
      title="会话管理"
      width="600px"
    >
      <div class="session-list">
        <div class="session-item" v-for="session in sessions" :key="session.id">
          <div class="session-info">
            <div class="device-info">
              <el-icon><Monitor /></el-icon>
              <span>{{ session.device }}</span>
            </div>
            <div class="session-details">
              <p>IP地址: {{ session.ip }}</p>
              <p>最后活动: {{ formatDate(session.lastActivity) }}</p>
            </div>
          </div>
          <div class="session-actions">
            <el-tag v-if="session.current" type="success" size="small">当前会话</el-tag>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="terminateSession(session.id)"
            >
              终止会话
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, User, Monitor } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { authAPI } from '@/api/auth'
import { userAPI } from '@/api/user'
import { useRouter } from 'vue-router'

// 用户store
const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const showProfileEdit = ref(false)
const saveLoading = ref(false)
const passwordLoading = ref(false)
const sessionDialogVisible = ref(false)
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 用户信息
const userInfo = ref({
  id: '',
  account: '',
  avatar: '',
  isActived: true,
  createdAt: '',
  updatedAt: '',
  displayName: '',
  email: '',
  phone: '',
  role: '普通用户'
})

// 表单数据
const profileForm = reactive({
  account: '',
  displayName: '',
  email: '',
  phone: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const securitySettings = reactive({
  loginNotification: false,
  twoFactorAuth: false
})

// 会话数据
const sessions = ref([
  {
    id: 1,
    device: 'Chrome on Windows 10',
    ip: '192.168.1.100',
    lastActivity: new Date(),
    current: true
  },
  {
    id: 2,
    device: 'Safari on iPhone',
    ip: '192.168.1.101',
    lastActivity: new Date(Date.now() - 3600000),
    current: false
  }
])

// 表单验证规则
const profileRules = {
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' },
    { min: 2, max: 50, message: '显示名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const loadUserInfo = async () => {
  try {
    const response = await authAPI.getUserInfo()
    console.log('用户信息响应:', response)

    if (response.code === 200 && response.value) {
      const data = response.value
      userInfo.value = {
        id: data.ID || data.id || '',
        account: data.Account || data.account || '',
        avatar: data.Avatar || data.avatar || '',
        isActived: data.IsActived ?? data.isActived ?? true,
        createdAt: data.CreatedAt || data.createdAt || '',
        updatedAt: data.UpdatedAt || data.updatedAt || '',
        displayName: data.DisplayName || data.displayName || data.Account || data.account || '',
        email: data.Email || data.email || '',
        phone: data.Phone || data.phone || '',
        role: '普通用户'
      }

      // 填充表单数据
      profileForm.account = userInfo.value.account
      profileForm.displayName = userInfo.value.displayName
      profileForm.email = userInfo.value.email
      profileForm.phone = userInfo.value.phone

      console.log('处理后的用户信息:', userInfo.value)
    } else {
      console.error('获取用户信息失败:', response)
      ElMessage.error(response.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const handleEditProfile = () => {
  showProfileEdit.value = true
}

const handleSaveProfile = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    saveLoading.value = true

    const response = await userAPI.updateProfile(profileForm)

    if (response.code === 200) {
      ElMessage.success('保存成功')
      showProfileEdit.value = false
      await loadUserInfo()
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

const cancelEdit = () => {
  showProfileEdit.value = false
  // 重置表单数据
  profileForm.displayName = userInfo.value.displayName || userInfo.value.account || ''
  profileForm.email = userInfo.value.email || ''
  profileForm.phone = userInfo.value.phone || ''
}

const handleChangePassword = async () => {
  await passwordFormRef.value.validate();
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致');
    return;
  }
  passwordLoading.value = true;
  try {
    const res = await userAPI.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    });
    if (res.code === 200) {
      ElMessage.success('密码修改成功');
      resetPasswordForm();
      userStore.logout();
      router.push('/login');
    } else {
      ElMessage.error(res.msg || '密码修改失败');
    }
  } finally {
    passwordLoading.value = false;
  }
};

const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const handleSessionManagement = () => {
  sessionDialogVisible.value = true
}

const terminateSession = async (sessionId) => {
  try {
    await ElMessageBox.confirm(
      '确定要终止这个会话吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 这里需要调用后端API终止会话
    sessions.value = sessions.value.filter(session => session.id !== sessionId)
    ElMessage.success('会话已终止')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('终止会话失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return 'N/A'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG/GIF 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const uploadAvatar = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)

    const response = await userAPI.uploadAvatar(formData)

    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      await loadUserInfo() // 上传成功后刷新用户信息
    } else {
      ElMessage.error(response.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 生命周期
onMounted(() => {
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;

  .profile-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .profile-info {
      .avatar-section {
        text-align: center;
        margin-bottom: 20px;

        .avatar-wrapper {
          position: relative;
          display: inline-block;
          margin-bottom: 15px;

          .user-avatar {
            margin-bottom: 10px;
          }

          .avatar-uploader {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
          }

          &:hover .avatar-uploader {
            opacity: 1;
          }

          .upload-btn {
            font-size: 12px;
            padding: 4px 8px;
          }
        }

        .username {
          margin: 10px 0 5px 0;
          font-size: 18px;
          font-weight: bold;
        }

        .user-role {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }

      .info-list {
        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .label {
            color: #606266;
            font-weight: 500;
          }

          .value {
            color: #303133;
          }
        }
      }
    }
  }

  .setting-card {
    margin-bottom: 20px;

    .card-header {
      font-weight: bold;
    }

    .security-settings {
      .setting-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;

        .setting-info {
          h4 {
            margin: 0 0 5px 0;
            font-size: 16px;
          }

          p {
            margin: 0;
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }

  .session-list {
    .session-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      margin-bottom: 10px;

      .session-info {
        .device-info {
          display: flex;
          align-items: center;
          margin-bottom: 5px;

          .el-icon {
            margin-right: 8px;
            color: #409eff;
          }

          span {
            font-weight: 500;
          }
        }

        .session-details {
          p {
            margin: 2px 0;
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .session-actions {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
